package com.nidu.demo.web.oauth2;

import com.alibaba.cola.dto.PageResponse;
import com.alibaba.cola.dto.Response;
import com.alibaba.cola.dto.SingleResponse;
import com.alibaba.fastjson2.JSONArray;
import com.nidu.demo.base.BatchDeleteCmd;
import com.nidu.demo.oauth2.dto.OAuth2ClientAddCmd;
import com.nidu.demo.oauth2.dto.OAuth2ClientPageQry;
import com.nidu.demo.oauth2.dto.OAuth2ClientUpdateCmd;
import com.nidu.demo.oauth2.api.OAuth2ClientService;
import com.nidu.demo.oauth2.dto.OAuth2ClientCO;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.HashSet;
import java.util.List;

/**
 * OAuth2客户端管理 Controller
 */
@Tag(name = "管理后台 - OAuth2客户端")
@RestController
@RequestMapping("/oauth2/clients")
@Validated
@RequiredArgsConstructor
public class OAuth2ClientController {

    private final OAuth2ClientService service;

    @Operation(summary = "创建OAuth2客户端", description = "创建新的OAuth2客户端")
    @PostMapping
    @PreAuthorize("@ss.hasPermission('oauth2:client:create')")
    public SingleResponse<OAuth2ClientCO> addClient(@RequestBody OAuth2ClientAddCmd cmd) {
        return service.add(cmd);
    }

    @Operation(summary = "更新OAuth2客户端", description = "更新OAuth2客户端的信息")
    @PutMapping("/{id}")
    @PreAuthorize("@ss.hasPermission('oauth2:client:update')")
    public SingleResponse<OAuth2ClientCO> updateClient(@PathVariable Long id, @RequestBody OAuth2ClientUpdateCmd cmd) {
        cmd.setId(id);
        return service.update(cmd);
    }

    @Operation(summary = "删除OAuth2客户端", description = "根据 ID 删除OAuth2客户端")
    @DeleteMapping("/{id}")
    @PreAuthorize("@ss.hasPermission('oauth2:client:delete')")
    public Response deleteClient(@PathVariable Long id) {
        return service.delete(id);
    }

    @Operation(summary = "批量删除OAuth2客户端", description = "根据 ID 列表删除多个OAuth2客户端")
    @PostMapping("/batch")
    @PreAuthorize("@ss.hasPermission('oauth2:client:delete')")
    public Response deleteClients(@RequestBody BatchDeleteCmd cmd) {
        List<Long> ids = JSONArray.parseArray(cmd.getDelete(), Long.class);
        return service.delete(new HashSet<>(ids));
    }

    @Operation(summary = "获取OAuth2客户端详情", description = "根据 ID 获取OAuth2客户端详细信息")
    @GetMapping("/{id}")
    @PreAuthorize("@ss.hasPermission('oauth2:client:query')")
    public SingleResponse<OAuth2ClientCO> getClientById(@PathVariable Long id) {
        return service.getById(id);
    }

    @Operation(summary = "分页查询OAuth2客户端", description = "分页获取OAuth2客户端信息")
    @GetMapping("/page")
    @PreAuthorize("@ss.hasPermission('oauth2:client:query')")
    public PageResponse<OAuth2ClientCO> pageClient(OAuth2ClientPageQry qry) {
        return service.page(qry);
    }
}
